from django.shortcuts import render,redirect,HttpResponse
from app.models import *
from django.db.models import Q
# Create your views here.
def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    if request.method == "POST":
        uname = request.POST.get('uname')
        pwd = request.POST.get('pwd')
        user = U_user.objects.filter(Q(uname=uname) & Q(pwd=pwd)).last()
        if user:
            return redirect('index')
        else:
            return redirect('login')
def index(request):
    uname=request.GET.get("uname")
    if uname is not None:
        list=U_user.objects.filter(uname__contains=uname)
    else:
        list=U_user.objects.all()
    return render(request,'index.html',{"list":list,"uname":uname})

def del_user(request,id):
    id=U_user.objects.get(id=id)
    id.delete()
    return redirect('index')

def edit_user(request,id):
    if request.method == "GET":
        user = U_user.objects.get(id=id)
        ro=Jue.objects.all()
        return render(request, 'edit_user.html', {"user": user,"ro":ro})
    if request.method == "POST":
        user = U_user.objects.get(id=id)
        uname = request.POST.get("uname")
        truename = request.POST.get("truename")
        pwd = request.POST.get("pwd")
        tel = request.POST.get("tel")
        sex = request.POST.get("sex")
        roleid = request.POST.get("roleid")
        address = request.POST.get("address")
        user.uname=uname
        user.truename=truename
        user.pwd=pwd
        user.tel=tel
        user.sex=sex
        user.roleid_id=roleid
        user.address=address
        user.save()
        return redirect('index')

def add_user(request):
    if request.method == "GET":
        ro=Jue.objects.all()
        return render(request, 'add_user.html', {"ro":ro})
    if request.method == "POST":
        uname = request.POST.get("uname")
        truename = request.POST.get("truename")
        pwd = request.POST.get("pwd")
        tel = request.POST.get("tel")
        sex = request.POST.get("sex")
        roleid = request.POST.get("roleid")
        address = request.POST.get("address")
        user=U_user(uname=uname,truename=truename,pwd=pwd,tel=tel,sex=sex,roleid_id=roleid,address=address)
        if uname and truename and pwd and tel and address is not None:
            user.save()
            return redirect('index')
        else:
            return HttpResponse("不能输入空")